/*
 * Author:  Copyright (c) 2013 Toby
 * E-Mail:  smurffit@gmail.com
 * Web:     https://code.google.com/p/chrome-mfi-filter4kiva/
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see <http://www.gnu.org/licenses/>.
 */

'use strict';

$(function()
{
	$('#tabs').tabs();
});

var txtrealHidden = document.getElementById('realHidden');
var txtcolorHidden = document.getElementById('colorHidden');
var txtcolorHighlight = document.getElementById('colorHighlight');
var chkshowRatingStars = document.getElementById('showRatingStars');
var chkstate = document.getElementById('state');

function mfi(id, name, rating, blocked, highlight, cat)
{
	this.id = id;
	this.name = name;
	this.rating = rating;
	this.blocked = blocked;
	this.highlight = highlight;
	this.cat = cat;
}

var storage = chrome.storage.local;
var res;
var bg = chrome.extension.getBackgroundPage();
// Saves options to localStorage.
function save_options(callback)
{
	var trends_dom = document.getElementById('mfi_list').getElementsByTagName('input');
	var regExSource = [];
	var regExHighlight = [];

	for ( var i = 0, len = trends_dom.length; i < len; i++)
	{
		var id = trends_dom[i].id;
		var blocked = trends_dom[i].checked;
		var highlight = false;

		for ( var j = 0, lem = res.length; j < lem; j++)
		{
			if (id == res[j].id)
			{
				res[j].blocked = blocked;
				res[j].cat = document.getElementById(id.concat('c')).value;
				highlight = document.getElementById(id.concat('d')).checked;
				res[j].highlight = highlight;
				if (blocked)
				{
					regExSource.push(res[j].name);
				}
				else if (highlight)
				{
					regExHighlight.push(res[j].name);
				}
				break;
			}
		}
	}

	bg
			.saveMfiList(
					res,
					function()
					{
						bg
								.saveRegEx(
										regExSource,
										regExHighlight,
										function()
										{
											// Update status to let user know
											// options were saved.
											var status = document.getElementById('status');
											status.innerHTML = 'Options Saved. Please reload all open Kiva tabs for the changes to take effect.';
											setTimeout(function()
											{
												status.innerHTML = '';
											}, 10000);
											saveSettings(function()
											{
												saveSettings(function()
												{
													callback();
												});
											});
										});
					});
}
function saveSettings(callback)
{
	bg.config.colorFilteredHide = txtrealHidden.value;
	bg.config.colorFilteredShow = txtcolorHidden.value;
	bg.config.colorHighlighted = txtcolorHighlight.value;
	bg.config.showRatingStars = chkshowRatingStars.checked;
	bg.config.block = chkstate.checked;

	bg
			.saveConfig(function()
			{
				bg
						.loadConfig(function()
						{
							// Update
							// status
							// to
							// let
							// user
							// know
							// options
							// were
							// saved.
							var status = document.getElementById('status');
							status.innerHTML = 'Options Saved. Please reload all open Kiva tabs for the changes to take effect.';
							setTimeout(function()
							{
								status.innerHTML = '';
							}, 5000);
							callback();
						});
			});
}
// Restores form box state to saved value from localStorage.
function restore_options()
{
	bg.loadMfiList(false, function(result)
	{
		if (result !== undefined)
		{
			res = result;
			createCheckbox();
		}
		else
		{
			fetch();
		}
		dl();
	});

	txtrealHidden.value = bg.config.colorFilteredHide;
	txtcolorHidden.value = bg.config.colorFilteredShow;
	txtcolorHighlight.value = bg.config.colorHighlighted;
	chkshowRatingStars.checked = bg.config.showRatingStars;
	chkstate.checked = bg.config.block;
}

function fetchFeed(callback)
{
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function()
	{
		if ((xhr.readyState == 4) && (xhr.status == 200))
		{
			var data = xhr.responseText;
			var list = data.substring(data.indexOf('<tbody'), data.indexOf('</table>'))
					.split('<tr');
			res = extractData(list);
			createCheckbox();
			save_options(callback);
		}
	};
	var url = 'http://www.kiva.org/partners';
	xhr.open('GET', url, true);
	xhr.send();
};

function extractData(list)
{
	// mfi(id, name, rating, blocked, highlight, cat)
	// TODO fetch partner count and check if we find the same amount
	var re = new Array(list.length - 1);
	var regex = /<h1 class=\"name\"><a href=\"http:\/\/www\.kiva\.org\/partners\/(\d{1,6})\">(.{3,160})<\/a><\/h1>[\s\S]*<div class=\"partnerRating .{0,40}\" title=\"Partner Risk Rating:(.{1,20})\">/m;
	for ( var i = 1, len = list.length; i < len; i++)
	{
		// trends_dom.innerText += list[i];
		var results = regex.exec(list[i]);

		if (results)
		{
			re[i - 1] = new mfi(results[1], results[2], results[3].replace(/\s/, ''), false, false,
					'');
			// re += results[1] + " / " + results[2] + "\n";
			// list[i].substring(list[i].indexOf("<div
			// class=\"info\">"),list[i].indexOf("<div class=\"timeOnKiva\">"));
		}
	}
	return re;
}

function createCheckbox()
{
	if (!res)
	{
		// return;
	}
	var trends_dom = document.getElementById('mfi_list');
	var ratings = bg.getRatingsMap(res);
	var ratingImg = bg.getRatingImgMap(ratings);

	for ( var i = 0, len = res.length; i < len; i++)
	{
		var cellBlock = document.getElementById(res[i].id);
		var cellHighlight = document.getElementById(res[i].id + 'd');
		var cellName = document.getElementById(res[i].id + 'b');

		if (!cellBlock)
		{
			cellBlock = document.createElement('input');
			cellBlock.type = 'checkbox';

			cellHighlight = document.createElement('input');
			cellHighlight.type = 'checkbox';

			var cellRating = document.createElement('span');
			cellRating.innerHTML = ratingImg[res[i].rating];

			cellName = document.createTextNode(res[i].name.substring(0, 80));
			var cellComment = document.createElement('input');
			cellComment.type = 'text';
			cellBlock.checked = res[i].blocked;
			cellBlock.id = res[i].id;

			cellHighlight.checked = res[i].highlight;
			cellHighlight.id = res[i].id + 'd';

			cellName.id = res[i].id + 'b';

			cellComment.setAttribute('value', res[i].cat);
			cellComment.setAttribute('size', '40');
			cellComment.id = res[i].id + 'c';

			var tr = trends_dom.appendChild(document.createElement('tr'));
			var td1 = tr.appendChild(document.createElement('td'));
			var td2 = tr.appendChild(document.createElement('td'));
			var td3 = tr.appendChild(document.createElement('td'));
			var td4 = tr.appendChild(document.createElement('td'));
			var td5 = tr.appendChild(document.createElement('td'));

			td1.appendChild(cellBlock);
			td1.className = 'centered';
			td2.appendChild(cellHighlight);
			td2.className = 'centered';
			td3.appendChild(cellRating);
			td3.className = 'centered';
			td4.appendChild(cellName);
			td5.appendChild(cellComment);
		}
		cellBlock.value = res[i].name;
		cellBlock.name = res[i].name;
	}
}

function fetch()
{
	var status = document.getElementById('status');
	status.innerHTML = 'Fetching Field Partner...';
	fetchFeed(function()
	{
		status.innerHTML = '';
	});
}

function reset()
{
	if (confirm('This will discard all changes you ever made in this dialog and reset the extension to factory defaults - continue?'))
	{
		storage.clear(function(items)
		{
			// none
		});
		res = null;
		alert('All settings have been removed!');
		window.location.reload();
	}
	else
	{
		alert('Reset cancelled!');
	}
}

var a = document.getElementById('dbdl');

document.body.addEventListener('dragstart', function(e)
{
	var a = e.target;
	if (a.classList.contains('dragout'))
	{
		e.dataTransfer.setData('DownloadURL', a.dataset.downloadurl);
	}
}, false);

document.body.addEventListener('dragend', function(e)
{
	var a = e.target;
	if (a.classList.contains('dragout'))
	{
		cleanUp(a);
	}
}, false);

document.addEventListener('keydown', function(e)
{
	if (e.keyCode == 27)
	{
		// Esc
		document.querySelector('details').open = false;
	}
	else if (e.shiftKey && (e.keyCode == 191))
	{
		// shift + ?
		document.querySelector('details').open = true;
	}
}, false);

var cleanUp = function(a)
{
	// Need a small delay for the revokeObjectURL to work properly.
	setTimeout(function()
	{
		window.URL.revokeObjectURL(a.href);
	}, 1500);
};

var dl = function()
{
	window.URL = window.webkitURL || window.URL;
	window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;

	a.download = 'db.json';
	a.href = window.URL.createObjectURL(new Blob([ JSON.stringify(res) ], {
		type : 'text/plain'
	}));

	a.dataset.downloadurl = [ 'text/plain', a.download, a.href ].join(':');
	a.draggable = true;

	a.classList.add('dragout');

	a.onclick = function(e)
	{
		if ('disabled' in this.dataset)
		{
			return false;
		}
		cleanUp(this);
	};
};

document.addEventListener('DOMContentLoaded', restore_options);
document.querySelector('#save').addEventListener('click', function()
{
	save_options();
});
document.querySelector('#save2').addEventListener('click', function()
{
	save_options();
});
document.querySelector('#fetch').addEventListener('click', fetch);
document.querySelector('#reset').addEventListener('click', reset);
